package cn.sxw.ld.module.user.controller;

import cn.sxw.ld.common.dto.R;
import cn.sxw.ld.module.user.pojo.User;
import cn.sxw.ld.module.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * ClassName:UserController
 * Package:cn.sjxy.graduation.controller
 * Description:
 *
 * @Date:2022/6/24 16:41
 * @Author:SXW
 */

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 功能：发送手机验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        boolean result = userService.toSendMsg(user, session);
        if (result) {
            return R.success("短信发送成功！");
        }
        return R.error("次数过多请于24小时候重试！");
    }

    /**
     * 登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        try {
            User user = userService.login(map, session);
            if (user != null) {
                return R.success(user);
            }
            return R.error("登录失败！");
        } catch (Exception e) {
            log.error("登录后台出错:'\n'{}", e.getMessage());
            return R.error("系统繁忙，请稍后再试~~");
        }


    }

    /**
     * 登出系统
     *
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginOut(HttpServletRequest request) {
        try {
            // 将保存在 Session 中的数据清除
            request.getSession().removeAttribute("user");
            return R.success("成功退出！");
        } catch (Exception e) {
            log.error("退出系统出错:'\n'{}", e.getMessage());
            return R.error("系统繁忙，请稍后再试~~");
        }

    }

    /**
     * 通过用户 id 获取用户详细信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<User> getUserById(@PathVariable String id) {
        try {
            return R.success(userService.getById(id));
        } catch (Exception e) {
            log.error("通过用户 id 获取用户详细信息:'\n'{}", e.getMessage());
            return R.error("系统繁忙，请稍后再试~~");
        }

    }


    /**
     * 回传 user ，保存到数据库
     *
     * @param user
     * @return
     */
    @PutMapping
    public R<String> updateUser(@RequestBody User user) {
        try {
            userService.updateUser(user);
            return R.success("修改成功！");
        } catch (Exception e) {
            log.error("修改员工信息出错:'\n'{}", e.getMessage());
            return R.error("系统繁忙，请稍后再试~~");
        }

    }
}

